package org.ktjiaoyu.controller;

import jakarta.annotation.Resource;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Jane
 * @date 2025-02-10 8:53
 */
@Controller
public class UserController {

    @Resource
    private AuthenticationManager authenticationManager;

    @ResponseBody
    @GetMapping("/test")
    public String test(){
        return "test......";
    }
    @ResponseBody
    @GetMapping("/goods")
    public String goods(){
        return "goods......";
    }

    @GetMapping("/tologin")  //去
    public String tologin(){
        System.out.println("tologin");
        return "wsjlogin";
    }

    @RequestMapping("/doLogin")  //执行
    public String dologin(@RequestParam(value = "username",name = "username") String username,
                          @RequestParam(value = "password",name = "password") String password
    ){
        System.out.println("doLogin");

        //获取所有的权限列表
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,password);

        //调用认证方法
        Authentication authenticate = authenticationManager.authenticate(token);

        //看登录后的用户信息以及权限列表
        Object principal = authenticate.getPrincipal();

        System.out.println("权限列表:");
        System.out.println(principal);


        return "main";

    }
    @RequestMapping("/toError")  //去
    public String toError(){
        System.out.println("toError");
        return "error";
    }

    @RequestMapping("/toMain")  //去
    public String toMain(){
        System.out.println("toMain");
        return "main";
    }

    @Secured("ROLE_laoshi")
    @RequestMapping("/toMain1")  //去
    public String toMain1(){
        System.out.println("toMain1");
        return "main1";
    }

    //@Secured("ROLE_xiaozhang")
    @PreAuthorize("hasRole('ROLE_xiaozhang')") //请求方法前进行校验是否有权限
    @RequestMapping("/toMain2")  //
    @ResponseBody// 去
    public String toMain2(){
        return "main2...";
    }


    @RequestMapping("/user/list")  //L0601
    public String user_list(){
        return "list";
    }

    @Secured("user:add")
    @RequestMapping("/user/add")
    public String user_add(){
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();

        System.out.println("权限列表-user-add: "+ authentication.getAuthorities());


        return "add";
    }

}
